import {AxiosInstance, AxiosResponse, InternalAxiosRequestConfig} from "axios";
import store from "@/store";
import {isEmpty} from "@/utils";
import reLogin from "@/request/reLogin";
import {$notify} from "@plat";

let whiteList: string[] = ['/sys/login'];

export default [{
  hook(instance: AxiosInstance) {
    instance.interceptors.request.use((config: InternalAxiosRequestConfig) => this.onRequest(config),
      (error) => this.onRequestError(error));

    instance.interceptors.response.use((response: AxiosResponse) => this.onResponse(response),
      (error) => this.onResponseError(error))
  },
  onRequest(config: InternalAxiosRequestConfig): InternalAxiosRequestConfig {
    //@ts-ignore
    if (whiteList.includes(config.url)) {
      return config;
    }
    try {
      if (this.hasToken()) {
        config.headers['X-Access-Token'] = store.getters.token;
        config.headers['X-Tenant-Id'] = store.getters.userInfo.tenantId;
      } else {
        reLogin('请登录!');
      }
    } catch (e) {
      console.error(e);
    }
    return config;
  },
  hasToken() {
    return !isEmpty(store?.getters?.token) && !isEmpty(store?.getters?.userInfo?.tenantId);
  },
  onRequestError(error: any): void {
  },
  onResponse(response: AxiosResponse): AxiosResponse {
    this.checkResponse(response);
    return response.data;
  },
  checkResponse(response: any) {
    if (response?.data?.message.indexOf('重新登录') !== -1) {
      reLogin(response?.data?.message);
      return
    }
    //全局系统报错提示
    // if (response?.data?.success === false && response?.data?.code !== 200) {
    //   $notify({
    //     title: '系统报错, 请联系管理员',
    //     message: response?.data?.message,
    //     type: "error"
    //   })
    // }
  },
  onResponseError(error: any) {
    this.checkResponse(error?.response);
  }
}]